<template>
  <AuModal
    v-model="showTreePopup"
    :title="t('issue.title')"
    width="600px"
    :padding="false"
    @handleConfirm="handleTreeConfirm"
    @close="handleTreeClose"
  >
    <div
      class="flex flex-col py-[30px] px-[16px] text-[--autata-font-gray2-color]"
    >
      <div class="flex">
        <div class="label flex-grow leading-[30px] text-right pr-[20px]">
          {{
            deviceIdType == "ATT-G"
              ? t("issue.store_list")
              : t("issue.device_list")
          }}
        </div>
        <div class="w-[440px]">
          <!--          />-->
          <el-input
            v-model="query"
            :placeholder="t('issue.filter_placeholder')"
            @input="onQueryChanged"
          />
          <vxe-card
            v-loading="loading"
            class="w-full mt-2 py-[8px] h-[342px]"
            :padding="false"
          >
            <el-tree-v2
              ref="treeRef"
              :data="treeData"
              :props="treeProps"
              :filter-method="filterMethod"
              :default-expanded-keys="expandedKeys"
              :item-size="38"
              show-checkbox
              :height="320"
            />
          </vxe-card>
          <!--          <el-cascader-->
          <!--            ref="treeRef"-->
          <!--            v-model="groupId"-->
          <!--            :options="treeData"-->
          <!--            v-bind="cascadeProps"-->
          <!--            style="width: 100%"-->
          <!--            @change="handleChange"-->
          <!--          />-->
        </div>
      </div>
      <!--      <div v-if="deviceIdType === 'ATT-G'" class="flex mt-[20px]">-->
      <!--        <div class="label flex-grow leading-[30px] text-right pr-[20px]">-->
      <!--          下发方式-->
      <!--        </div>-->
      <!--        <div class="w-[440px]">-->
      <!--          <vxe-radio-group v-model="isAuto">-->
      <!--            <vxe-radio :label="true" content="门店自动拉取" />-->
      <!--            <vxe-radio :label="false" content="门店手动拉取" />-->
      <!--          </vxe-radio-group>-->
      <!--        </div>-->
      <!--      </div>-->
      <div class="flex mt-[20px]">
        <div class="label flex-grow leading-[30px] text-right pr-[20px]">
          {{ t("table.note") }}
        </div>
        <div class="w-[440px]">
          <el-input
            v-model="note"
            type="textarea"
            maxlength="100"
            :placeholder="t('issue.note_placeholder')"
          />
        </div>
      </div>
    </div>
  </AuModal>
</template>

<script setup lang="ts">
import { computed, reactive, ref, toRef, watch } from "vue";
import { ElTreeV2, ElMessage } from "element-plus";
import type {
  TreeKey,
  TreeNode
} from "element-plus/es/components/tree-v2/src/types";
import { getReleaseSelect, TreeProp } from "@/api/teaInfuser/formula";
import { AuModal } from "@/components/AuModal";
import { isFunction, isNumber } from "@pureadmin/utils";
import { useI18n } from "vue-i18n";

defineOptions({
  name: "IssueModal"
});

const { t } = useI18n();
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  versionId: {
    type: [Number, String]
  },
  deviceIdType: {
    type: String,
    default: "ATT-"
  },
  releaseFn: {
    type: Array as PropType<() => Promise<void>>,
    default: () => []
  },
  isOnlyShowStore: {
    type: Boolean,
    default: false
  },
  isJsonString: {
    type: Boolean,
    default: false
  },
  confirmCheckFn: {
    type: Function,
    default: null
  }
});
const emit = defineEmits(["update:modelValue"]);

const showTreePopup = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});
const query = ref("");
const note = ref("");
const isAuto = ref(true);
const groupId = ref([]);
const cascadeProps = ref({
  placeholder: `请选择${props.deviceIdType == "ATT-G" ? "门店" : "设备"}`,
  showAllLevels: true,
  collapseTags: true,
  maxCollapseTags: 2,
  collapseTagsTooltip: true,
  filterable: true,
  props: {
    value: "id",
    label: "name",
    children: "children",
    emitPath: true,
    // checkStrictly: true,
    multiple: true
  }
});

const loading = ref(false);
const expandedKeys = ref<TreeKey[]>([]);
let flatKeys = [];
const [versionRelease, versionReleaseList] = props.releaseFn;
const treeData = ref<TreeProp[]>([]);
const treeProps = {
  value: "id",
  label: "name",
  class: "custom-node",
  children: "children"
};
const checkedData = ref([]);
const treeRef = ref<InstanceType<typeof ElTreeV2>>();
const backendData = ref([]);
const checkedKeys = ref([]);
const storeReleaseList = ref([]);
const nodeMap = reactive(new Map());
const storeToGroupMap = reactive(new Map());
const groupSet = ref(new Set());

const isTrue = ["ATT-S", "ATT-G"].includes(props.deviceIdType);

function transformData(data: TreeProp[]) {
  // flatKeys = [];
  return data.map(group => {
    let transformedGroup = {
      id: group.id,
      name: group.name,
      label: group.name,
      deviceId: group.name,
      type: isNumber(group.parent_id) ? "group" : group.type,
      disabled: false,
      children: group.children ? [...group.children] : []
    };
    flatKeys.push({
      id: group.id,
      name: group.name
    });
    expandedKeys.value.push(group.id);
    // 将门店的 device_list 合并到 store 对象中作为子节点
    if (group.store_list && group.store_list.length > 0) {
      group.store_list.forEach(store => {
        flatKeys.push({
          id: store.id,
          name: store.name
        });
        let storeWithDevices = {
          id: store.id,
          name: store.name,
          label: store.name,
          deviceId: store.name,
          parentId: group.id,
          type: "store",
          children: props.isOnlyShowStore
            ? undefined
            : store.device_list
                .filter(device =>
                  device.device_model.includes(props.deviceIdType)
                )
                .map(device => {
                  flatKeys.push({
                    id: device.device_id,
                    name: device.device_id
                  });
                  return {
                    id: device.device_id,
                    name: device.device_id,
                    label: device.device_id,
                    parentId: store.id,
                    deviceId: device.device_id,
                    type: "device",
                    device_status: device.device_status,
                    children: []
                  };
                })
        };
        transformedGroup.children.push(storeWithDevices as any);
      });
    } else {
      if (
        !transformedGroup.children?.length &&
        transformedGroup.type !== "device" &&
        !props.isOnlyShowStore
      ) {
        transformedGroup.disabled = true;
      }
    }

    // 递归处理 children 中的数据
    if (transformedGroup.children && transformedGroup.children.length > 0) {
      transformedGroup.children = transformData(transformedGroup.children);
    }

    return transformedGroup as any;
  });
}

const getTreeData = async () => {
  loading.value = true;
  groupId.value = [];
  try {
    const res = await getReleaseSelect();
    if (res.code === 200) {
      treeData.value = transformData(res.data);
      console.log(treeData.value);
      buildNodeMaps(treeData.value);
      treeRef.value!?.setExpandedKeys(expandedKeys.value);
      loading.value = false;

      const listRes = await versionReleaseList({
        versionId: String(props.versionId),
        version: String(props.versionId),
        idList: JSON.stringify([
          {
            id: props.versionId
          }
        ])
      });
      if (listRes.code === 200) {
        if (props.deviceIdType === "ATT-S") {
          // groupId.value = keys;
          const releaseList = (listRes.data?.formulaReleaseList ?? []).filter(
            v =>
              (groupSet.value.has(v.group_id) || v.store_id) &&
              !(v.store_id && v.group_id)
          );
          // 过滤既有store_id和group_id的数据，formulaReleaseList 和 storeReleaseList 都有store_id的数据
          storeReleaseList.value = (
            listRes.data?.storeReleaseList ?? []
          ).filter(
            v =>
              !(v.store_id && v.group_id) &&
              !releaseList.find(
                h => h.store_id === v.store_id && h.version === v.version
              )
          );

          // 如果没有分组ID的长度 直接勾选门店
          const releaseHasGroupLen = releaseList.filter(v => v.group_id).length;
          backendData.value = [
            ...releaseList
            // ...(releaseHasGroupLen ? storeReleaseList : [])
          ];
          console.log(groupSet.value, releaseList, backendData.value);
          treeRef.value!.setCheckedKeys([]);
          processCheckLogic();
        } else {
          note.value = listRes.data[0]?.note ?? "";
          let keys = [];
          if (props.isOnlyShowStore) {
            keys = [
              ...listRes.data.map(v => v.store_id),
              ...listRes.data.map(v => v.group_id)
            ].filter(v => v);
          } else {
            const key = isTrue ? "device_id" : "deviceId";
            const devices = listRes.data.map(v => v[key]);
            keys = flatKeys
              .filter(v => devices.includes(v.name))
              .map(v => v.id);
          }
          treeRef.value!.setCheckedKeys(keys);
        }
      }
    }
  } catch (e) {
    console.error(e);
    loading.value = false;
  }
};

// 构建节点映射和store到group的映射
const buildNodeMaps = (nodes, parentGroupId = null) => {
  nodes.forEach(node => {
    // 添加到节点映射
    nodeMap.set(node.id, node);
    if (node.type === "group") {
      // 如果是group节点，递归处理其子节点，并传递当前groupId
      if (node.children && node.children.length) {
        buildNodeMaps(node.children, node.id);
      }
      groupSet.value.add(node.id);
    } else if (node.type === "store") {
      // 如果是store节点，记录它属于哪个group
      if (parentGroupId) {
        storeToGroupMap.set(node.id, parentGroupId);
      }
    } else if (node.children && node.children.length) {
      // 其他类型节点，继续递归但不改变parentGroupId
      buildNodeMaps(node.children, parentGroupId);
    }
  });
};

// 分析后端数据
const selectedGroups = new Set(); // 被选中的group_id集合
const selectedStores = new Set(); // 被选中的store_id集合
// 处理勾选逻辑
const processCheckLogic = () => {
  selectedGroups.clear();
  selectedStores.clear();
  // 收集所有被选中的group_id和store_id
  backendData.value.forEach(item => {
    if (item.group_id) {
      selectedGroups.add(item.group_id);
    } else if (item.store_id) {
      selectedStores.add(item.store_id);
    }
  });

  // 找出所有被选中group下的所有store
  const storesFromGroups = getStoresFromGroups(selectedGroups);
  // 分组下没有门店的情况
  const emptyStoreGroups = getEmptyStoreGroups(selectedGroups);

  // 合并所有应该被勾选的store_id
  checkedKeys.value = [
    ...Array.from(selectedStores),
    ...storesFromGroups,
    ...emptyStoreGroups
  ];

  console.log("checkedKeys.value", checkedKeys.value);
  // 如果没有group被选中，则直接设置勾选
  if (!selectedGroups.size) {
    treeRef.value!.setCheckedKeys(checkedKeys.value);
    return;
  }

  // 处理冲突情况：如果store同时被独立选中和通过group选中
  resolveCheckConflicts();
};

const getEmptyStoreGroups = groupIds => {
  const emptyStoreGroups = [];

  groupIds.forEach(groupId => {
    const group = nodeMap.get(groupId);
    if (group && group.type === "group") {
      const children = group.children || []; // 处理children可能为undefined的情况
      const hasStore = children.some(child => child.type === "store");
      const isLeaf = children.length === 0; // 判断是否为叶子节点（无子节点）

      // 只有当group是叶子节点且没有store子节点时才加入结果
      if (isLeaf && !hasStore) {
        emptyStoreGroups.push(groupId);
      }
    }
  });
  console.log(emptyStoreGroups);
  return emptyStoreGroups;
};

// 获取所有选中group下的store节点id
const getStoresFromGroups = groupIds => {
  const storeIds = new Set();

  groupIds.forEach(groupId => {
    const group = nodeMap.get(groupId);
    if (group) {
      getAllStoresInNode(group, storeIds);
    }
  });

  return Array.from(storeIds);
};

// 递归获取节点下所有store类型节点的id
const getAllStoresInNode = (node, storeIds) => {
  if (node.type === "store") {
    storeIds.add(node.id);
  } else if (node.children && node.children.length) {
    node.children.forEach(child => {
      getAllStoresInNode(child, storeIds);
    });
  }
};

// 处理勾选冲突
const resolveCheckConflicts = () => {
  // 获取所有store节点所属的group
  const checkedStoreGroups = new Map(); // store_id -> group_id映射

  checkedKeys.value.forEach(storeId => {
    const groupId = storeToGroupMap.get(storeId);
    if (groupId) {
      if (!checkedStoreGroups.has(groupId)) {
        checkedStoreGroups.set(groupId, new Set());
      }
      checkedStoreGroups.get(groupId).add(storeId);
    }
  });

  // 检查是否有同一个store被不同的group选中
  const storesToKeep = new Set();

  // 遍历每个被勾选的store
  checkedKeys.value.forEach(storeId => {
    // 检查该store属于哪个group
    const store = storeReleaseList.value.find(v => v.store_id == storeId);
    if (!store) {
      storesToKeep.add(storeId);
    }
    // const groupId = storeToGroupMap.get(storeId);
    //
    // // 如果该store有对应的group
    // if (groupId) {
    //   // 获取该group中已被勾选的stores
    //   const groupStores = checkedStoreGroups.get(groupId);
    //
    //   // 如果这个store是该group中唯一被勾选的，或者是后端明确指定要勾选的
    //   if (
    //     (groupStores && groupStores.size === 1) ||
    //     !isStoreExplicitlyChecked(storeId)
    //   ) {
    //     storesToKeep.add(storeId);
    //   }
    // } else {
    //   // 没有对应的group或是独立勾选的store
    //   storesToKeep.add(storeId);
    // }
  });

  // 更新最终勾选的keys
  checkedKeys.value = Array.from(storesToKeep);
  console.log(checkedKeys.value);

  treeRef.value!.setCheckedKeys(checkedKeys.value);
};

// 检查store是否是明确被选中的（不是通过group被选中）
const isStoreExplicitlyChecked = storeId => {
  return backendData.value.some(item => item.store_id === storeId);
};

// 处理节点勾选事件
const handleCheck = (data, checkState) => {
  const { checked } = checkState;

  // 处理group节点的勾选
  if (data.type === "group") {
    if (checked) {
      // 如果group被选中，选中其下所有store节点
      const storeIds = [];
      getAllStoresInNode(data, new Set(storeIds));

      // 取消当前已勾选的所有store节点
      const currentCheckedKeys = treeRef.value.getCheckedKeys();
      const keysToRemove = currentCheckedKeys.filter(
        key => nodeMap.get(key) && nodeMap.get(key).type === "store"
      );

      treeRef.value.setCheckedKeys(
        keysToRemove.filter(
          key =>
            !storeToGroupMap.has(key) || storeToGroupMap.get(key) === data.id
        )
      );

      // 勾选当前group下的所有store
      storeIds.forEach(id => {
        treeRef.value.setChecked(id, true);
      });
    } else {
      // 如果group被取消选中，取消其下所有store节点
      const storeIds = [];
      getAllStoresInNode(data, new Set(storeIds));
      storeIds.forEach(id => {
        treeRef.value.setChecked(id, false);
      });
    }
  } else if (data.type === "store") {
    // 处理store节点的勾选
    if (checked) {
      // 获取该store所属的group
      const groupId = storeToGroupMap.get(data.id);
      if (groupId) {
        // 获取该group下所有其他已勾选的store
        const groupNode = nodeMap.get(groupId);
        if (groupNode) {
          const groupStores = [];
          getAllStoresInNode(groupNode, new Set(groupStores));

          // 取消选中该group下的其他store
          const currentCheckedKeys = treeRef.value.getCheckedKeys();
          groupStores.forEach(storeId => {
            if (storeId !== data.id && currentCheckedKeys.includes(storeId)) {
              treeRef.value.setChecked(storeId, false);
            }
          });
        }
      }
    }
  }

  // 保存当前勾选状态
  saveCheckState();
};

// 保存当前勾选状态
const saveCheckState = () => {
  // 获取当前所有勾选的节点
  const checkedNodes = treeRef.value.getCheckedNodes();
  const checkedStores = checkedNodes.filter(node => node.type === "store");

  // 可以在这里处理保存逻辑，例如更新到后端
  console.log("当前选中的store节点：", checkedStores);
};

function hasChinese(text) {
  const reg = /[\u4e00-\u9fff]/;
  return reg.test(text);
}

const onQueryChanged = (query: string) => {
  treeRef.value!.filter(query);
};

const handleTreeConfirm = async () => {
  if (isFunction(props.confirmCheckFn)) {
    const res = await props.confirmCheckFn({ version: props.versionId });
    if (!res) {
      return;
    }
  }
  const checkedNodes = treeRef.value!.getCheckedNodes();
  const sourceArray = [],
    sourceStoreArray = [],
    sourceGroupArray = [];
  let sourceSubmitArray = {};
  if (checkedNodes.length == 0) {
    sourceArray.push({ deviceId: "0" });
  }
  console.log(checkedNodes, storeToGroupMap);
  if (props.deviceIdType === "ATT-S") {
    // 先获取接口返回的group_id，塞到参数里
    for (const v of selectedGroups) {
      sourceGroupArray.push({ group_id: v, containStoreId: [] });
    }
    const selectedMap = new Map();
    checkedNodes.forEach(v => {
      if (v.type === "group") {
        // 去除重复添加
        if (!selectedGroups.has(v.id)) {
          sourceGroupArray.push({ group_id: v.id, containStoreId: [] });
        }
        !selectedMap.has(v.id) && selectedMap.set(v.id, 0);
      } else if (v.type === "store") {
        // 为了剔除不勾选的分组，把sourceGroupArray多余的group去掉
        const gId = storeToGroupMap.get(v.id);
        selectedMap.has(gId)
          ? selectedMap.set(gId, selectedMap.get(gId) + 1)
          : selectedMap.set(gId, 1);

        // 把勾选的store添加到group中
        if (sourceGroupArray.find(item => item.group_id === gId)) {
          const index = sourceGroupArray.findIndex(
            item => item.group_id === gId
          );
          if (index !== -1) {
            sourceGroupArray[index].containStoreId.push({ store_id: v.id });
          } else {
            sourceGroupArray.push({
              group_id: gId,
              containStoreId: [{ store_id: v.id }]
            });
          }
        } else {
          sourceStoreArray.push({ store_id: v.id });
        }
      }
      // sourceSubmitArray =
      //   sourceGroupArray.length > 0
      //     ? { groupIdList: JSON.stringify(sourceGroupArray) }
      //     : { storeIdList: JSON.stringify(sourceStoreArray) };
    });
    for (const v of sourceGroupArray) {
      if (!selectedMap.has(v.group_id)) {
        sourceGroupArray.splice(sourceGroupArray.indexOf(v), 1);
      }
    }
    sourceSubmitArray = {
      groupIdList: JSON.stringify(sourceGroupArray),
      storeIdList: JSON.stringify(sourceStoreArray)
    };
    console.log(selectedMap, sourceSubmitArray);
  } else {
    checkedNodes.forEach(v => {
      // const item = v.data;
      if ("deviceId" in v) {
        if (!hasChinese(v.deviceId)) {
          // 根据要求的格式构造新对象，并添加到新数组中
          sourceArray.push(
            isTrue ? { device_id: v.deviceId } : { deviceId: v.deviceId }
          );
        }
      }

      if (v.type === "store") {
        // 根据要求的格式构造新对象，并添加到新数组中
        sourceStoreArray.push({ store_id: String(v.id) });
      }
    });
  }
  const param = {
    "ATT-S": {
      versionList: JSON.stringify([
        {
          version: props.versionId,
          ...sourceSubmitArray,
          // deviceIdList: JSON.stringify(sourceSubmitArray),
          note: note.value
        }
      ])
    },
    "ATT-G": {
      formulaList: JSON.stringify([
        {
          version: props.versionId,
          storeIdList: sourceStoreArray,
          note: note.value
        }
      ]),
      is_auto: isAuto.value,
      hiddenDeviceType: true
    },
    "ATT-": [
      {
        versionId: props.versionId,
        deviceList: sourceArray,
        note: note.value
      }
    ]
  };

  console.log(param);
  const params = isTrue ? param[props.deviceIdType] : param["ATT-"];
  versionRelease(params).then(res => {
    if (res.code === 200) {
      //VxeUI.modal.message({ content: "操作成功", status: "success" });
      // for (const checkedNode of checkedNodes) {
      //   treeRef.value!.setChecked(checkedNode.id, false);
      // }
      emit("update:modelValue", false);
      ElMessage({
        message: t("notice.operation_success"),
        grouping: true,
        type: "success"
      });
    }
  });
};

const handleTreeClose = () => {
  // const checkedNodes = treeRef.value!.getCheckedNodes();
  // for (const checkedNode of checkedNodes) {
  //   treeRef.value!.setChecked(checkedNode.id, false);
  // }
  emit("update:modelValue", false);
};

const handleChange = () => {};

const filterMethod = (query: string, node: TreeNode) => {
  return node[treeProps.label]!.includes(query);
};

watch([() => props.modelValue, () => props.versionId], (val, id) => {
  checkedData.value = [];
  if (val) {
    getTreeData();
  }
});
</script>

<style lang="scss">
.custom-node {
  .el-tree-node__content {
    --el-checkbox-height: 38px;
  }
}

/* 隐藏选择框中的标签文本 */
.el-cascader .el-tag {
  width: 20px;
  overflow: hidden;
  visibility: hidden;
}

/* 但保留数量标识 */
.el-cascader .el-tag__close {
  visibility: visible;
}

.el-cascader .el-tag.el-tag--info {
  width: auto;
  visibility: visible;
}
</style>
